package com.xxzb.pack0820;

import java.io.*;

//序列化和反序列化  重点
//序列化：将Java对象从内存中保存到硬盘中的过程，它是一个写入的过程
//反序列化：将保存到硬盘的Java对象重新转换成Java对象，它是一个读取的过程
public class DemoH {
    public static void 序列化() throws Exception{
        //产生对象
        Person person=new Person(1,"张三",'男');
        Person person2=new Person(1,"张三2",'女');
        Person person3=new Person(1,"张三3",'男');
        //序列化就是把这个person对象保存到硬盘中，并且持久化保存 ,后缀名任意
        File file=new File("F:\\yongpangaofeng\\p.obj");
        OutputStream out=new FileOutputStream(file);
        //产生一个对于对象进行写入的操作对象
        ObjectOutputStream oos=new ObjectOutputStream(out);
        //将对象写入到指定文件中
        oos.writeObject(person);
        //这里可以持久化多个对象到一个文件
        oos.writeObject(person2);
        oos.writeObject(person3);
        oos.close();
        out.close();
    }

    public static void 反序列化() throws Exception{
        File file=new File("F:\\yongpangaofeng\\p.obj");
        InputStream in=new FileInputStream(file);
        //产生一个对对象进行读取的操作对象
        ObjectInputStream ois=new ObjectInputStream(in);
        //获取到这个对象
        Object obj = ois.readObject();
        Object obj2 = ois.readObject();
        Object obj3 = ois.readObject();
        System.out.println(obj);
        System.out.println(obj2);
        System.out.println(obj3);
        ois.close();
        in.close();
    }

    //了解
    public static Student student=new Student(1,"张三");
    public static void 序列化2() throws Exception{
        File file=new File("F:\\yongpangaofeng\\p.obj");
        OutputStream out=new FileOutputStream(file);
        ObjectOutputStream oos=new ObjectOutputStream(out);
        student.writeExternal(oos);
        oos.close();
        out.close();
    }

    public static void 反序列化2() throws Exception{
        File file=new File("F:\\yongpangaofeng\\p.obj");
        InputStream in=new FileInputStream(file);
        ObjectInputStream ois =new ObjectInputStream(in);
        student.readExternal(ois);
        ois.close();
        in.close();
    }
    public static void main(String[] args) throws Exception {
//        序列化();
//        反序列化();
//        序列化2();
        反序列化2();
    }
}
